<template>
  <el-select v-model="sval" 
      :disabled="disabled" 
      :class="className"
      :multiple="multiple"
      :collapse-tags="collapseTags"
      filterable 
      :popper-class="popperClass" 
      :clearable="clearable"
      :placeholder="placeholder" :style="{ width }" @change="onChcange">
      <el-option v-for="dt in lists" :key="dt.value" :value="dt.value" :label="dt.label" />
  </el-select>
</template>
<script setup>
import { ref, onMounted, watch } from "vue"
import { getSelectList } from '@/api/select'

const props = defineProps({
  modelValue: '',
  width: {
      type: String,
      default: '100%'
  },
  params:{  // 查询条件
      type:Object,
      default:{}
  },
  disabled: {
      type: Boolean,
      default: false
  },
  multiple: {
      type: Boolean,
      default: false
  },
  clearable:{
    type: Boolean,
    default: true
  },
  collapseTags:{
    type: Boolean,
      default: false
  },
  placeholder:{
    type: String,
      default: '请选择'
  },
  loadingChange:{
    type: Boolean,
    default: true
  }
})
const emit = defineEmits(['update:modelValue', 'change','changeName'])
const sval = ref('')
const lists = ref('')

onMounted(() => {
  getTableData()
})

watch(() => props.modelValue, (n, o) => {
  sval.value = n
})

const getTableData = async () => {
  const res = await getSelectList({ page: 1, limit: 100, ...props.params})
  if (res) {
      lists.value = res || []
      sval.value = props.modelValue ?props.modelValue: '' // 设置默认选项
      window.setTimeout(() => {
        if(props.loadingChange){
          onChcange()
        }
      }, 500);
  }
}

const onChcange = () => {
  emit('update:modelValue', sval.value)
  emit('change', sval.value)
  if (sval.value && !props.multiple) {
      const item = lists.value.find((ele) => {
          return ele.value === sval.value
      })
      emit('changeName', item.label)
  }else if(sval.value && props.multiple){
    let str =''
    let list = []
    sval.value?.forEach(item => {
      const obj = lists.value.find((ele) => {
          return ele.value == item
      })
      if(obj){
        str += obj.label+','
        list.push(obj)
      }
    })
      emit('changeList', list)
      emit('changeName', str.slice(0, -1))
  }else{
    emit('changeName', null)
  }
}

defineExpose({ getTableData })

</script>

<style scoped lang="scss"></style>